/*
 * @Author: i@douxuefeng.cn
 * @Date: 2021-12-18 16:06:41
 * @LastEditTime: 2021-12-23 17:50:30
 * @LastEditors: i@douxuefeng.cn
 * @Description: 初始化app
 * @FilePath: \go-im\app\init_app.go
 */

package app

import (
	"io/fs"
	"os"
	"time"

	"gitee.com/douxuefeng/go-im/cache"
	comm "gitee.com/douxuefeng/go-utils"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

var Config fs.File

func InitApp() {
	var err error
	viper.SetConfigType("yml")
	if err = viper.ReadConfig(Config); err != nil {
		panic(err)
	}
	folders := viper.GetStringSlice("folders")
	if len(folders) > 0 {
		var newFile = comm.NewFile
		for _, v := range folders {
			if !newFile.IsExist(v) {
				err = newFile.CreateFile(v)
				if err != nil {
					panic(err)
				}
			}
		}
	}
	// 初始化日志系统
	logrus.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: viper.GetString("timeFormat"),
	})
	logrus.SetOutput(os.Stdout)
	logrus.SetLevel(logrus.DebugLevel)
	f, _ := rotatelogs.New(
		viper.GetString("logFolder")+time.Now().Format("2006-01-02")+".log",
		rotatelogs.WithLinkName(viper.GetString("logFolder")+"logs.log"),
		rotatelogs.WithMaxAge(time.Duration(viper.GetInt("logMaxAge")*24)*time.Hour),
		rotatelogs.WithRotationTime(time.Duration(24)*time.Hour),
	)
	logrus.SetOutput(f)
	cache.InitRedis()
}
